package com.sduept.nwld.dataserver.controller.fault;

import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.fault.entity.*;
import com.sduept.bigdata.fault.manager.*;
import com.sduept.cim.model.extend.LineSegment;
import com.sduept.cim.model.wires.Breaker;
import com.sduept.cim.query.service.LineTowerQueryService;
import com.sduept.core.ParamManager;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.entity.SystemParameter;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.permission.entity.DepartmentEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.TabChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import java.util.*;

@Named
@ViewScoped
public class DcLineFaultReportController extends FaultReportEditAbstractController {

	private static final long serialVersionUID = -5494341361896590389L;

	@Autowired
	private SuperDAO dao;
	@Autowired
	private CimManager cm;
	@Autowired
	private FaultRecordPersistManager frpm;
	@Autowired
	private FaultReportPersistManager fpm;
	@Autowired
	private FaultRecordQueryManager frqm;
	@Autowired
	private FaultReportQueryManager fqm;
	@Autowired
	private FaultEditLockManager lockM;
	@Autowired
	private ParamManager cacheM;
	@Autowired
	private LineTowerQueryService lineTowerQueryService;

	private FaultReportMain faultReportMain = new FaultReportMain();
	private FaultReportStationDetail firstStationDetail;
	private FaultReportStationDetail secondStationDetail;
	// 第一个站的动作元件
	private List<FaultReportComponentDetail> firstComponentList = new ArrayList<>();
	// 第二个站的动作元件
	private List<FaultReportComponentDetail> secondComponentList = new ArrayList<>();
	private String currentSelectStation = null;
	private boolean showFirstTableAllColumns = false;
	private boolean showSecondTableAllColumns = false;
	private Comparator<FaultReportComponentDetail> componentComparator = null;
	// 第一个站选择的动作元件
	private List<FaultReportComponentDetail> firstSelectComponentList;
	// 第二个站选择的动作元件
	private List<FaultReportComponentDetail> secondSelectComponentList;

	private FaultRecord fr = null;
	private boolean firstStationEdit; // 第一个变电站编辑锁
	private boolean secondStationEdit; // 第二个变电站编辑锁

	/**
	 * 初始化故障信息
	 * 
	 * 将FaultRecord查询由使用SuperDAO改为使用 FaultRecordQueryManager查询 （20190109 zhangqi）
	 */
	@PostConstruct
	private void init() {
		SystemParameter parameter = cacheM.get(ParamDesc.FAULT_REPORT_EDIT_INTERVAL);
		if (parameter != null && StringUtils.isNotEmpty(parameter.getValue())) {
			timingInteval = Integer.parseInt(parameter.getValue());
		}
		initBackButton();
		componentComparator = new Comparator<FaultReportComponentDetail>() {
			@Override
			public int compare(FaultReportComponentDetail o1, FaultReportComponentDetail o2) {
				if (o1.getActionTime() > o2.getActionTime()) {
					return 1;
				} else if (o1.getActionTime() == o2.getActionTime()) {
					return 0;
				} else {
					return -1;
				}
			}
		};
		faultId = getParameter("faultId");
		if (StringUtils.isNotEmpty(faultId)) {
			fr = frqm.findById(faultId);
			faultReportMain = fqm.getFaultReportMain(faultId);
			if (faultReportMain == null || StringUtils.isEmpty(fr.getStationId())) {
				LineSegment line = cm.getLineSegmentById(fr.getEquipment_id());
				if (line != null) {
					fr.setStationId(line.getStartST());
					fr.setStationName(line.getStartStName());
					fr.setStationId2(line.getEndST());
					fr.setStationName2(line.getEndStName());
				}
				frpm.saveFaultRecord(new FaultRecordWrapper(false, false, fr));
				// 重新获取一下faultReportMain
				faultReportMain = fqm.getFaultReportMain(faultId);
			}
			for (FaultReportStationDetail sdetail : faultReportMain.getFaultReportStationDetails()) {
				if (StringUtils.isNotEmpty(fr.getStationId()) && fr.getStationId().equals(sdetail.getStationId())) {
					firstStationDetail = sdetail;
					if (firstStationDetail.getFirstFault() != null)
						firstStationDetail.setFirstFaultMs(firstStationDetail.getFirstFault() / 1000f);// 设置初次故障时间
					if (firstStationDetail.getRecloseFault() != null)
						firstStationDetail.setRecloseFaultMs(firstStationDetail.getRecloseFault() / 1000f);// 设置合于故障时间

					currentSelectStation = firstStationDetail.getStationId();
					firstComponentList.addAll(firstStationDetail.getFaultReportComponentDetails());
					Collections.sort(firstComponentList, componentComparator);
				} else if (StringUtils.isNotEmpty(fr.getStationId2())
						&& fr.getStationId2().equals(sdetail.getStationId())) {
					secondStationDetail = sdetail;
					if (secondStationDetail.getFirstFault() != null)
						secondStationDetail.setFirstFaultMs(secondStationDetail.getFirstFault() / 1000f);
					if (secondStationDetail.getRecloseFault() != null)
						secondStationDetail.setRecloseFaultMs(secondStationDetail.getRecloseFault() / 1000f);

					secondComponentList.addAll(secondStationDetail.getFaultReportComponentDetails());
					Collections.sort(secondComponentList, componentComparator);
				}
			}
			if (firstStationDetail != null) {
				stationId1 = firstStationDetail.getStationId();
			}
			if (secondStationDetail != null) {
				stationId2 = secondStationDetail.getStationId();
			}
			loadAttachmentList(faultReportMain.getFaultRecord(), stationId1, stationId2);
		}
	}

	/**
	 * 保存故障报告信息
	 */
	public void saveReportMain() {
		try {
			String str = "";
			if (firstStationDetail != null) {
				str += firstStationDetail.getStationName() + "：";
				Double xbcj1 = firstStationDetail.getManualFaultRangingFirst() == null ? 0
						: firstStationDetail.getManualFaultRangingFirst();
				Double xbcj2 = firstStationDetail.getManualFaultRangingSecond() == null ? 0
						: firstStationDetail.getManualFaultRangingSecond();
				Double xbcj3 = firstStationDetail.getManualFaultRangingThird() == null ? 0
						: firstStationDetail.getManualFaultRangingThird();
				if (xbcj1 == 0 && xbcj2 == 0 && xbcj3 == 0) {
					str += "无行波测距；";
				} else {
					if (xbcj1 > 0)
						str += "第一套：" + xbcj1 + "km，";
					if (xbcj2 > 0)
						str += "第二套：" + xbcj2 + "km，";
					if (xbcj3 > 0)
						str += "第三套：" + xbcj3 + "km，";
					str = str.substring(0, str.lastIndexOf("，")) + "；";
				}
				firstStationDetail.setFirstFault(firstStationDetail.getFirstFaultMs() == null ? 0
						: (int) (firstStationDetail.getFirstFaultMs() * 1000));// 由于页面显示的是毫秒,数据库存入的是微妙所以需要扩大1000倍
				firstStationDetail.setRecloseFault((int) (firstStationDetail.getRecloseFaultMs() == null ? 0
						: firstStationDetail.getRecloseFaultMs() * 1000));
			}
			if (secondStationDetail != null) {
				// 设置行波测距
				str += secondStationDetail.getStationName() + "：";
				Double xbcj1 = secondStationDetail.getManualFaultRangingFirst() == null ? 0
						: secondStationDetail.getManualFaultRangingFirst();
				Double xbcj2 = secondStationDetail.getManualFaultRangingSecond() == null ? 0
						: secondStationDetail.getManualFaultRangingSecond();
				Double xbcj3 = secondStationDetail.getManualFaultRangingThird() == null ? 0
						: secondStationDetail.getManualFaultRangingThird();
				if (xbcj1 == 0 && xbcj2 == 0 && xbcj3 == 0) {
					str += "无行波测距";
				} else {
					if (xbcj1 > 0)
						str += "第一套：" + xbcj1 + "km，";
					if (xbcj2 > 0)
						str += "第二套：" + xbcj2 + "km，";
					if (xbcj3 > 0)
						str += "第三套：" + xbcj3 + "km，";
					str = str.substring(0, str.lastIndexOf("，"));
				}
				secondStationDetail.setFirstFault(secondStationDetail.getFirstFaultMs() == null ? 0
						: (int) (secondStationDetail.getFirstFaultMs() * 1000));
				secondStationDetail.setRecloseFault(secondStationDetail.getRecloseFaultMs() == null ? 0
						: (int) (secondStationDetail.getRecloseFaultMs() * 1000));
			}
			fpm.saveFaultReportComponentDetail(firstStationDetail, firstComponentList);
			fpm.saveFaultReportComponentDetail(secondStationDetail, secondComponentList);
			if (StringUtils.isNotEmpty(str))
				fr.setRanging(str);
			else
				fr.setRanging(null);
			Set<FaultReportStationDetail> set = new HashSet<>();
			if (firstStationDetail != null)
				set.add(firstStationDetail);
			if (secondStationDetail != null)
				set.add(secondStationDetail);
			if (set.size() > 0)
				faultReportMain.setFaultReportStationDetails(set);
			faultReportMain = dao.createOrUpdate(faultReportMain, FaultReportMain.class);
//			1.在保存的时候，调用getTowerNo()方法
//			2.返回一个interger类型
			List<Double> distances = getStartAndEndDistances(firstStationDetail, secondStationDetail);
			Integer distanse = lineTowerQueryService.getTowerNo(distances.get(0), distances.get(1),
					fr.getEquipment_id());
//			3.set进faultReport 的startPole
			fr.setStartPole(distanse);
			frpm.saveFaultRecordOnly(fr);
			addSuccessMessage("保存成功！");
		} catch (Exception e) {
			e.printStackTrace();
			addErrorMessage("保存失败！");
		}
	}

	public List<String> completeProtectName(String query) {
		List<String> result = new ArrayList<String>();
		result.add("主一保护");
		result.add("主二保护");
		result.add("主三保护");
		String eid = faultReportMain.getFaultRecord().getEquipment_id();
		if (StringUtils.isNotEmpty(eid)) {
			List<Breaker> list = null;
			if (firstStationDetail != null && currentSelectStation.equals(firstStationDetail.getStationId())) {
				list = cm.getBreakersById(eid, firstStationDetail.getStationId());
			} else if (secondStationDetail != null && currentSelectStation.equals(secondStationDetail.getStationId())) {
				list = cm.getBreakersById(eid, secondStationDetail.getStationId());
			}
			if (list != null) {
				for (Breaker b : list) {
					result.add(b.getName() + "断路器保护");
				}
			}
		}
		return result;
	}

	/**
	 * 重置故障报告填写人
	 */
	public void resetreportPersonAndUnit() {
		if (StringUtils.isNotEmpty(currentSelectStation)) {
			if (currentSelectStation.equals(firstStationDetail.getStationId())) {
				firstStationDetail.setReportPerson(null);
				firstStationDetail.setReportUnit(null);
			} else if (currentSelectStation.equals(secondStationDetail.getStationId())) {
				secondStationDetail.setReportPerson(null);
				secondStationDetail.setReportUnit(null);
			}
		}
	}

	/**
	 * 重置故障报告审核人
	 */
	public void resetreportAuditor() {
		if (StringUtils.isNotEmpty(currentSelectStation)) {
			if (currentSelectStation.equals(firstStationDetail.getStationId())) {
				firstStationDetail.setReviewer(null);
			} else if (currentSelectStation.equals(secondStationDetail.getStationId())) {
				secondStationDetail.setReviewer(null);
			}
		}
	}

	public List<String> completeActionComponentRemark(String query) {
		List<String> results = new ArrayList<String>();
		results.add("故障初");
		results.add("重合后");
		return results;
	}

	/**
	 * 添加动作元件
	 */
	public void addActionComponent() {
		FaultReportComponentDetail fd = new FaultReportComponentDetail();
		fd.setId(ObjectId.get().toString());
		fd.setStatus(1);
		if (firstStationDetail != null && currentSelectStation.equals(firstStationDetail.getStationId())) {
			firstComponentList.add(fd);
			Collections.sort(firstComponentList, componentComparator);
		} else if (secondStationDetail != null && currentSelectStation.equals(secondStationDetail.getStationId())) {
			secondComponentList.add(fd);
			Collections.sort(secondComponentList, componentComparator);
		}
	}

	/**
	 * 标签页切换事件
	 *
	 * @param event
	 */
	public void onTabChange(TabChangeEvent event) {
		String title = event.getTab().getTitle();
		if (firstStationDetail != null && title.equals(firstStationDetail.getStationName()))
			currentSelectStation = firstStationDetail.getStationId();
		else if (secondStationDetail != null && title.equals(secondStationDetail.getStationName()))
			currentSelectStation = secondStationDetail.getStationId();
	}

	/**
	 * 删除第一个站选择的 动作元件详情
	 */
	public void deleteFirstSelectComponentList() {
		if (firstSelectComponentList != null) {
			for (FaultReportComponentDetail detail : firstSelectComponentList) {
				if (StringUtils.isNotEmpty(detail.getId()))
					fpm.deleteFaultReportComponentDetail(detail.getId());
				firstComponentList.remove(detail);
				firstStationDetail.getFaultReportComponentDetails().remove(detail);
			}
		}
	}

	/**
	 * 删除第二个站选择的 保护/断路器动作详情
	 */
	public void deleteSecondSelectComponentList() {
		if (secondSelectComponentList != null) {
			for (FaultReportComponentDetail detail : secondSelectComponentList) {
				if (StringUtils.isNotEmpty(detail.getId()))
					fpm.deleteFaultReportComponentDetail(detail.getId());
				secondComponentList.remove(detail);
				secondStationDetail.getFaultReportComponentDetails().remove(detail);
			}
		}
	}

	public void onUserDialogReturn() {
		PersonnelEntityBean user = getCurrentUser();
		DepartmentEntityBean group = user.getGroup();
		if (StringUtils.isNotEmpty(currentSelectStation)) {
			if (currentSelectStation.equals(firstStationDetail.getStationId())) {
				firstStationDetail.setReportPerson(user.getName());
				firstStationDetail.setReportUnit(group.getName());
			} else if (currentSelectStation.equals(secondStationDetail.getStationId())) {
				secondStationDetail.setReportPerson(user.getName());
				secondStationDetail.setReportUnit(group.getName());
			}
		}
		// }
	}

	/**
	 * 审核人选择回掉
	 *
	 * @param event
	 */
	public void onAuditorDialogReturn() {
		PersonnelEntityBean user = getCurrentUser();
		if (StringUtils.isNotEmpty(currentSelectStation)) {
			if (currentSelectStation.equals(firstStationDetail.getStationId())) {
				firstStationDetail.setReviewer(user.getName());
			} else if (currentSelectStation.equals(secondStationDetail.getStationId())) {
				secondStationDetail.setReviewer(user.getName());
			}
		}
		faultReportMain.setReviewer(user.getName());
		// }
	}

	/**
	 * 下载附件
	 */
	public void downloadAttachment() {
		file = getAttachmentFile(currentSelectStation);
		if (file == null) {
			addErrorMessage("该文件不存在");
		}
	}

	/**
	 * 删除附件
	 */
	public void deleteAttachment() {
		deleteAttachment(currentSelectStation);
		loadAttachmentList(faultReportMain.getFaultRecord(), stationId1, stationId2);
	}

	/**
	 * 上传附件
	 */
	public void handleFileUpload(FileUploadEvent event) {
		handleFileUpload(event, currentSelectStation);
	}

	/**
	 * 编辑变电站的时间戳
	 */
	public void pushTiming() {
		if (firstStationEdit) {
			lockM.gainLock(faultId + firstStationDetail.getId(), new Date().getTime(), getCurrentUser().getId());
		}
		if (secondStationEdit) {
			lockM.gainLock(faultId + secondStationDetail.getId(), new Date().getTime(), getCurrentUser().getId());
		}
	}

	/**
	 * 变电站编辑
	 * 
	 * @param stationId
	 */
	public void editStation(String stationId) {
		// 如果该资源可用
		if (checkEditPageIsUsed(faultId + stationId)) {
			if (stationId.equals(firstStationDetail.getId())) {
				firstStationEdit = true;
			} else if (stationId.equals(secondStationDetail.getId())) {
				secondStationEdit = true;
			}
		} else { // 如果该资源不可用
			addErrorMessage("变电站正在被【 " + gainOwner(faultId + stationId) + " 】编辑，请等待！");
		}
	}

	public FaultReportMain getFaultReportMain() {
		return faultReportMain;
	}

	public void setFaultReportMain(FaultReportMain faultReportMain) {
		this.faultReportMain = faultReportMain;
	}

	public FaultReportStationDetail getFirstStationDetail() {
		return firstStationDetail;
	}

	public void setFirstStationDetail(FaultReportStationDetail firstStationDetail) {
		this.firstStationDetail = firstStationDetail;
	}

	public FaultReportStationDetail getSecondStationDetail() {
		return secondStationDetail;
	}

	public void setSecondStationDetail(FaultReportStationDetail secondStationDetail) {
		this.secondStationDetail = secondStationDetail;
	}

	public boolean isShowFirstTableAllColumns() {
		return showFirstTableAllColumns;
	}

	public void setShowFirstTableAllColumns(boolean showFirstTableAllColumns) {
		this.showFirstTableAllColumns = showFirstTableAllColumns;
	}

	public boolean isShowSecondTableAllColumns() {
		return showSecondTableAllColumns;
	}

	public void setShowSecondTableAllColumns(boolean showSecondTableAllColumns) {
		this.showSecondTableAllColumns = showSecondTableAllColumns;
	}

	public List<FaultReportComponentDetail> getFirstComponentList() {
		return firstComponentList;
	}

	public void setFirstComponentList(List<FaultReportComponentDetail> firstComponentList) {
		this.firstComponentList = firstComponentList;
	}

	public List<FaultReportComponentDetail> getSecondComponentList() {
		return secondComponentList;
	}

	public void setSecondComponentList(List<FaultReportComponentDetail> secondComponentList) {
		this.secondComponentList = secondComponentList;
	}

	public void setFirstSelectComponentList(List<FaultReportComponentDetail> firstSelectComponentList) {
		this.firstSelectComponentList = firstSelectComponentList;
	}

	public List<FaultReportComponentDetail> getSecondSelectComponentList() {
		return secondSelectComponentList;
	}

	public void setSecondSelectComponentList(List<FaultReportComponentDetail> secondSelectComponentList) {
		this.secondSelectComponentList = secondSelectComponentList;
	}

	public List<FaultReportComponentDetail> getFirstSelectComponentList() {
		return firstSelectComponentList;
	}

	public String getCurrentSelectStation() {
		return currentSelectStation;
	}

	public void setCurrentSelectStation(String currentSelectStation) {
		this.currentSelectStation = currentSelectStation;
	}

	public FaultRecord getFr() {
		return fr;
	}

	public void setFr(FaultRecord fr) {
		this.fr = fr;
	}

	public boolean isFirstStationEdit() {
		return firstStationEdit;
	}

	public void setFirstStationEdit(boolean firstStationEdit) {
		this.firstStationEdit = firstStationEdit;
	}

	public boolean isSecondStationEdit() {
		return secondStationEdit;
	}

	public void setSecondStationEdit(boolean secondStationEdit) {
		this.secondStationEdit = secondStationEdit;
	}

}
